module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      validate: {
        len: [3, 50],
        notEmpty: true
      }
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
        notEmpty: true
      }
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'password_hash',
      validate: {
        notEmpty: true,
        len: [6, 255]
      }
    },
    nickname: {
      type: DataTypes.STRING(50),
      allowNull: true,
      validate: {
        len: [1, 50]
      }
    },
    avatar: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'avatar_url'
    },
    theme_preference: {
      type: DataTypes.ENUM('light', 'dark', 'auto'),
      defaultValue: 'auto'
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'banned'),
      defaultValue: 'active',
      field: 'is_active'
    },
    last_login_at: {
      type: DataTypes.DATE,
      allowNull: true
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
    bio: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '个人简介'
    },
    gender: {
      type: DataTypes.ENUM('male', 'female', 'secret'),
      defaultValue: 'secret'
    },
    birthday: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    location: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '所在地'
    },
    settings: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '用户设置'
    }
  }, {
    tableName: 'users',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        unique: true,
        fields: ['username']
      },
      {
        unique: true,
        fields: ['email']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['is_active']
      }
    ]
  });

  User.associate = (models) => {
    // 用户与分类的关联
    User.hasMany(models.Category, {
      foreignKey: 'user_id',
      as: 'categories',
      onDelete: 'CASCADE'
    });

    // 用户与标签的关联
    User.hasMany(models.Tag, {
      foreignKey: 'user_id',
      as: 'tags',
      onDelete: 'CASCADE'
    });

    // 用户与日记的关联
    User.hasMany(models.Diary, {
      foreignKey: 'user_id',
      as: 'diaries',
      onDelete: 'CASCADE'
    });

    // 用户与图片的关联
    User.hasMany(models.Image, {
      foreignKey: 'user_id',
      as: 'images',
      onDelete: 'CASCADE'
    });
  };

  // 实例方法
  User.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    delete values.password; // 不返回密码字段
    return values;
  };

  return User;
}; 